﻿using DDDSystem.Domain;
using DDDSystem.Domain.Shared;
using DDDSystem.Domain.Entities;
using Microsoft.EntityFrameworkCore;

namespace DDDSystem.EntityFrameworkCore;


/// <summary>
/// 基本字典仓储实现
/// </summary>
public class BasicDictionaryRepository : IBasicDictionaryRepository
{
    private PSIDbContext _context;

    public BasicDictionaryRepository(PSIDbContext context)
    {
        _context = context;       
    }

    /// <summary>
    /// 创建基础字典
    /// </summary>
    /// <param name="basicDictionary"></param>
    /// <returns></returns>
    public BasicDictionary Post(BasicDictionary basicDictionary)
    {
        using (_context)
        {
            _context.Add(basicDictionary);
            _context.SaveChanges();

            return basicDictionary;
        }
    }

    /// <summary>
    /// 修改基础字典
    /// </summary>
    /// <param name="basicDictionary"></param>
    /// <returns></returns>
    public int Put(Guid id, BasicDictionary basicDictionary)
    {
        using (_context)
        {
            var item = _context.BasicDictionaries.Where(b => b.ID == id).FirstOrDefault();

            if (item != null)
            {
                item.Sort = basicDictionary.Sort;
                item.Name = basicDictionary.Name;
                item.PinYinCode = basicDictionary.PinYinCode;
            }

            return _context.SaveChanges();
        }
    }

    /// <summary>
    /// 删除基础字典
    /// </summary>
    /// <param name="basicDictionary"></param>
    /// <returns></returns>
    public int Delete(Guid id)
    {
        using (_context)
        {
            var item = _context.BasicDictionaries.Where(b => b.ID == id).FirstOrDefault();

            if (item != null)
            {
                _context.Remove(item);
            }

            return _context.SaveChanges();
        }
    }

    /// <summary>
    /// 查询基础字典
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public IList<BasicDictionary> Get(BasicDictionaryType type)
    {
        using (_context)
        {
            var item = _context.BasicDictionaries.Where(b => b.Type == type).OrderBy(o => o.Sort).ToList();

            return item;
        }
    }
}

